<template>
  <div class="login-container">
    <div class="login-background">
      <div class="login-overlay"></div>
    </div>

    <div class="login-content">
      <div class="login-left">
        <div class="system-intro">
          <div class="logo-container">
            <div class="logo-icon-wrapper">
              <img src="../../assets/logo/logo.svg" alt="Logo" />
            </div>
          </div>
          <h1 class="system-name">阡陌智标</h1>
          <p class="system-slogan">高效·专业·智能</p>
          <div class="system-features">
            <div class="feature-item">
              <el-icon><Document /></el-icon>
              <span>AI辅助编写</span>
            </div>
            <div class="feature-item">
              <el-icon><Histogram /></el-icon>
              <span>智能结构生成</span>
            </div>
            <div class="feature-item">
              <el-icon><Share /></el-icon>
              <span>团队协同编辑</span>
            </div>
            <div class="feature-item">
              <el-icon><Files /></el-icon>
              <span>标书模板管理</span>
            </div>
          </div>
        </div>
      </div>

      <div class="login-right">
        <div class="login-form-container">
          <div class="login-header">
            <h2>{{ isLogin ? '账户登录' : '注册账户' }}</h2>
            <p>{{ isLogin ? '欢迎使用智能标书编写平台' : '创建一个新的账户' }}</p>
          </div>
          <!-- 登录表单 -->
          <el-form v-if="isLogin" ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="top">
            <el-form-item prop="username" label="用户名">
              <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" autocomplete="on" clearable />
            </el-form-item>

            <el-form-item prop="password" label="密码">
              <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" autocomplete="on" show-password />
            </el-form-item>

            <div class="login-options">
              <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
            </div>

            <div class="privacy-options">
              <el-checkbox v-model="loginForm.privacyAgreed">
                我已阅读并同意
                <el-button type="text" @click="showPrivacyPolicy">《隐私政策》</el-button>
              </el-checkbox>
            </div>

            <el-button :loading="loading" type="primary" class="login-button" @click.prevent="handleLogin"> 登录 </el-button>

            <div class="register-link">
              <span>还没有账户?</span>
              <el-button type="text" @click="toggleForm">立即注册</el-button>
            </div>
          </el-form>

          <!-- 注册表单 -->
          <el-form
            v-else
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="login-form"
            autocomplete="off"
            label-position="top"
          >
          <el-form-item prop="phone" label="手机号码">
              <el-input v-model="registerForm.phone" placeholder="请输入手机号码" prefix-icon="Phone" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item prop="username" label="用户名">
              <el-input v-model="registerForm.username" placeholder="请输入用户名" prefix-icon="User" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" prefix-icon="Message" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                autocomplete="off"
                show-password
              />
            </el-form-item>

            <el-form-item prop="confirmPassword" label="确认密码">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                prefix-icon="Lock"
                autocomplete="off"
                show-password
              />
            </el-form-item>

           <!--  <el-form-item prop="email" label="电子邮箱">
              <el-input v-model="registerForm.email" placeholder="请输入电子邮箱" prefix-icon="Message" autocomplete="off" clearable />
            </el-form-item>
 -->
            <el-button :loading="loading" type="primary" class="login-button" @click.prevent="handleRegister"> 注册 </el-button>

            <div class="register-link">
              <span>已有账户?</span>
              <el-button type="text" @click="toggleForm">返回登录</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 隐私政策对话框 -->
    <el-dialog v-model="privacyDialogVisible" title="阡陌智标™ 隐私政策" width="70%" append-to-body class="privacy-dialog">
      <PrivacyPolicyContent @agree="agreePrivacy" @close="privacyDialogVisible=false" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { User, Lock, Message, Document, Histogram, Share, Files } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import { login, register } from '@/api/auth';
import type { LoginData, RegisterForm } from '@/api/types';
import { getToken, setToken, removeToken } from '@/utils/auth'
import PrivacyPolicyContent from './components/PrivacyPolicyContent.vue';

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const rememberMe = ref(false);
const isLogin = ref(true);
const userStore = useUserStore();
const privacyDialogVisible = ref(false);

// 登录表单
const loginFormRef = ref<FormInstance>();
/* const loginForm = reactive({
  username: '',
  password: ''
}); */
const loginForm = reactive<LoginData>({
  username: '',
  password: '',
  rememberMe: false,
  privacyAgreed: false
});

const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
  ]
});

// 注册表单
const registerFormRef = ref<FormInstance>();
const registerForm = reactive<RegisterForm>({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: ''
});

// 密码确认验证
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const registerRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入11位有效的手机号码', trigger: 'blur' }
  ],
 /*  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的电子邮箱地址', trigger: 'blur' }
  ] */
});

// 切换登录/注册表单
const toggleForm = () => {
  isLogin.value = !isLogin.value;
};

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return;
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!loginForm.privacyAgreed) {
        ElMessage.warning('请阅读并同意隐私政策');
        return;
      }
      
      loading.value = true;

      try {
        // 调用实际登录API
        // await getCodeImg()
         const res:any = await login({
          username: loginForm.username,
          password: loginForm.password
         });

        console.log(res)
        // 保存token和用户信息
        setToken(res.data?.access_token)
        userStore.setToken(res.data?.access_token)
       /*  setToken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDI3MjA4NzcsInN1YiI6IjUifQ.c3LPKjLpPKocYq0jfSWeNa3nzImTok2wQg9');
        userStore.setToken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDI3MjA4NzcsInN1YiI6IjUifQ.c3LPKjLpPKocYq0jfSWeNa3nzImTok2wQg9'); */
        
        ElMessage.success('登录成功');
        
        // 跳转到目标页面或首页
        const redirect = route.query.redirect as string;
        router.push(redirect || '/dashboard');
      } catch (error: any) {
        console.error('登录失败:', error);
        ElMessage.error(error.response?.data?.message || '登录失败，请重试');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return;
  await registerFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      
      (async () => {
        try {
          // 调用注册API
          await register({
            username: registerForm.username,
            password: registerForm.password,
            email: registerForm.email,
            phone: registerForm.phone,
            id: '392130290',
            role: ['user']
          });
          
          ElMessage.success('注册成功，请登录');
          isLogin.value = true;
          
          // 清空注册表单
          Object.assign(registerForm, {
            username: '',
            password: '',
            confirmPassword: '',
            email: '',
            phone: ''
          });
        } catch (error: any) {
          console.error('注册失败:', error);
          ElMessage.error(error.response?.data?.message || '注册失败，请重试');
        } finally {
          loading.value = false;
        }
      })();
    }
  });
};

// 显示隐私政策
const showPrivacyPolicy = () => {
  privacyDialogVisible.value = true;
};

// 同意隐私政策
const agreePrivacy = () => {
  loginForm.privacyAgreed = true;
  privacyDialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
@use '../../styles/variables.scss' as *;

.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e0f2fe 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}

.login-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(29, 78, 216, 0.05) 100%);
}

.login-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0;
  max-width: 1200px;
  width: 100%;
  background: rgba(255, 255, 255, 0.95);
  border-radius: var(--ai-radius-xl);
  overflow: hidden;
  box-shadow: var(--ai-shadow-xl);
  backdrop-filter: var(--ai-blur-md);
  border: 1px solid var(--ai-border-light);
  position: relative;
  z-index: 1;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: var(--ai-gradient-primary);
  }
}

.login-left {
  background: linear-gradient(135deg, var(--ai-primary) 0%, var(--ai-secondary) 100%);
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: white;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.1) 50%, transparent 70%);
    animation: shimmer 4s infinite;
  }
}

.system-intro {
  position: relative;
  z-index: 1;
}

.logo-container {
  margin-bottom: 30px;
}

.logo-icon-wrapper {
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: var(--ai-radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  backdrop-filter: var(--ai-blur-sm);
  border: 2px solid rgba(255, 255, 255, 0.3);
  
  img {
    width: 50px;
    height: 50px;
   
  }
}

.system-name {
  font-size: 32px;
  font-weight: 800;
  margin: 0 0 16px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.system-slogan {
  font-size: 18px;
  margin: 0 0 40px 0;
  opacity: 0.9;
  font-weight: 500;
}

.system-features {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  max-width: 400px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: var(--ai-radius-md);
  backdrop-filter: var(--ai-blur-sm);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: var(--ai-transition);
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: translateY(-2px);
  }
  
  .el-icon {
    font-size: 20px;
    color: rgba(255, 255, 255, 0.9);
  }
  
  span {
    font-size: 14px;
    font-weight: 600;
    color: rgba(255, 255, 255, 0.9);
  }
}

.login-right {
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: rgba(255, 255, 255, 0.95);
}

.login-form-container {
  max-width: 400px;
  width: 100%;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 28px;
  font-weight: 700;
  color: var(--ai-text-primary);
  margin: 0 0 12px 0;
  background: var(--ai-gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-header p {
  font-size: 16px;
  color: var(--ai-text-secondary);
  margin: 0;
  line-height: 1.5;
}

.login-form {
  .el-form-item {
    margin-bottom: 24px;
  }
  
  .el-input {
    --el-input-height: 56px;
    
    .el-input__wrapper {
      background: var(--ai-bg-input) !important;
      border: 2px solid var(--ai-border-light) !important;
      border-radius: var(--ai-radius-md) !important;
      color: var(--ai-text-primary) !important;
      transition: var(--ai-transition) !important;
      
      &:hover {
        border-color: var(--ai-primary-light) !important;
        box-shadow: var(--ai-shadow-sm) !important;
      }
      
      &.is-focus {
        border-color: var(--ai-primary) !important;
        box-shadow: 0 0 0 3px var(--ai-primary-alpha) !important;
      }
    }
    
    .el-input__inner {
      height: 56px;
      font-size: 16px;
      color: var(--ai-text-primary) !important;
      
      &::placeholder {
        color: var(--ai-text-tertiary) !important;
      }
    }
    
    .el-input__prefix {
      color: var(--ai-text-secondary) !important;
    }
  }
  
  .el-form-item__label {
    font-size: 15px;
    font-weight: 600;
    color: var(--ai-text-secondary) !important;
    margin-bottom: 8px;
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 24px 0;
  
  .el-checkbox {
    --el-checkbox-font-size: 14px;
    color: var(--ai-text-secondary) !important;
    
    .el-checkbox__input.is-checked .el-checkbox__inner {
      background: var(--ai-primary) !important;
      border-color: var(--ai-primary) !important;
    }
  }
}

.privacy-options {
  margin: 24px 0;
  
  .el-checkbox {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: var(--ai-text-secondary) !important;
    
    .el-checkbox__input.is-checked .el-checkbox__inner {
      background: var(--ai-primary) !important;
      border-color: var(--ai-primary) !important;
    }
  }
  
  .el-button--text {
    padding: 0 4px;
    font-size: 14px;
    color: var(--ai-primary) !important;
    
    &:hover {
      color: var(--ai-primary-light) !important;
    }
  }
}

.login-button {
  width: 100%;
  height: 56px;
  font-size: 16px;
  font-weight: 600;
  border-radius: var(--ai-radius-md);
  margin: 24px 0;
  background: var(--ai-gradient-primary) !important;
  border: none;
  transition: var(--ai-transition) !important;
  position: relative;
  overflow: hidden;
  box-shadow: var(--ai-shadow-md);
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: var(--ai-shadow-lg);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.register-link {
  text-align: center;
  margin-top: 24px;
  
  span {
    color: var(--ai-text-secondary);
    font-size: 14px;
  }
  
  .el-button--text {
    color: var(--ai-primary) !important;
    font-weight: 600;
    
    &:hover {
      color: var(--ai-primary-light) !important;
    }
  }
}

/* 动画 */
@keyframes shimmer {
  0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
  100% { transform: translateX(100%) translateY(100%) rotate(45deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-content {
    grid-template-columns: 1fr;
    max-width: 500px;
  }
  
  .login-left {
    padding: 40px 30px;
  }
  
  .login-right {
    padding: 40px 30px;
  }
  
  .system-features {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 16px;
  }
  
  .login-left {
    padding: 30px 20px;
  }
  
  .login-right {
    padding: 30px 20px;
  }
  
  .system-name {
    font-size: 28px;
  }
  
  .system-slogan {
    font-size: 16px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }
}
</style>

